#!/usr/bin/perl -w

use strict;
use LWP::Simple;
use HTML::TreeBuilder;
binmode(STDIN, ':encoding(utf8)');
#binmode(STDOUT, ':encoding(utf8)');
binmode(STDERR, ':encoding(utf8)');
use DBI;

my $dsn="DBI:mysql:database=test;host=localhost;port=3306";
my $dbh= DBI->connect($dsn,"root","",{mysql_enable_utf8 => 1}) or die "Connection Error: $DBI::errstr\n";

my $fanhao;
my $name;
my $length;
my $PublishDate;
my $Publisher;

my $content=get('http://fanhao.org/') or die "could not get the page" ;

my $tree=HTML::TreeBuilder->new;

$tree->parse_content($content) or die "could not parse webpage" ;

$tree->eof();

    my $table=$tree->find_by_attribute("class","fanhao_list_table");
    
    my $tb=$table->look_down(_tag=>"tbody");
    
    my @items=$tb->look_down(_tag=>"td");
    
    my $i=0;
    
    foreach my $item(@items)
    
    {
        ;
        $item=$item->as_text();
        if ($i % 5 == 0 ) {
            $fanhao = $item;
        }        
        elsif ($i % 5 == 1) {
            $name = $item;
        }
        elsif($i % 5 == 2){
            $length=$item; 
        }
        elsif($i % 5==3){
            $PublishDate=$item;
        }
        elsif($i % 5==4){
            $Publisher=$item;
            print $Publisher;
            #my $SQL = "INSERT INTO `fanhao`.`fanhao` (`Fanhao`, `Name`, `Length`, `PublishDate`, `Publisher`) VALUES ($fanhao , $name ,$length , $PublishDate , $Publisher )";
            #print $dbh->quote($SQL);
            my $sth=$dbh->do("INSERT INTO `fanhao`.`fanhao` (`Fanhao`, `Name`,
            `Length`, `PublishDate`, `Publisher`) VALUES (?,?,?,?,?)",{},
            $fanhao,$name,$length,$PublishDate,$Publisher);
            #my $sth=$dbh->do($dbh->quote($SQL));
        }
        
        $i=$i+1;
    }
    
    $dbh-disconnect();
$tree->delete;

open(FILEHANDLE,">1.txt");

print FILEHANDLE $content;